package com.hooda.framework.factory;

import com.hooda.framework.annotations.Autowired;
import com.hooda.framework.annotations.Component;
import com.hooda.framework.annotations.Transaction;
import com.hooda.framework.aop.TransactionManager;

import java.lang.reflect.Method;

/**
 * @author zhangzp
 * @version 1.0, 2021/9/10
 */
@Component("transactionInterceptor")
public class TransactionMethodInterceptor implements MethodInterceptor {

    @Autowired
    private TransactionManager transactionManager;

    @Override
    public void before(Object target, Method method, Object[] args) throws Exception {
        if (isSupportTransaction(method)) {
            transactionManager.beginTransaction();
        }
    }

    @Override
    public void afterReturnning(Object target, Method method, Object[] args) throws Exception {
        if (isSupportTransaction(method)) {
            transactionManager.commit();
        }
    }

    @Override
    public void afterThrowing(Object target, Method method, Object[] args) throws Exception {
        if (isSupportTransaction(method)) {
            transactionManager.rollback();
        }
    }

    @Override
    public void after(Object target, Method method, Object[] args) throws Exception {

    }

    private boolean isSupportTransaction(Method method) {
        if (method.isAnnotationPresent(Transaction.class)) {
            return true;
        }
        return false;
    }
}
